import { showToast } from "vant";
import { ref } from "vue";

interface CheckJsApiResult {
  err_msg: string;
  checkResult:
    | {
        requestMerchantTransfer: boolean;
      }
    | string;
}

interface RedPacketResult {
  err_msg: string;
  [key: string]: any;
}

export const lanuchRedPacket = (
  packageStr: string,
  callback: (pullState: number) => void
): Promise<RedPacketResult> => {
  return new Promise((resolve, reject) => {
    window.WeixinJSBridge.invoke(
      "checkJsApi",
      {
        jsApiList: ["requestMerchantTransfer"]
      },
      function (res: CheckJsApiResult) {
        console.log("checkJsApi返回 ==> ", res);

        if (
          typeof res.checkResult === "string"
            ? res.checkResult.includes("true")
            : res.checkResult.requestMerchantTransfer
        ) {
          callback(1);
          // 支持，继续调用红包接口
          window.WeixinJSBridge.invoke(
            "requestMerchantTransfer",
            {
              mchId: import.meta.env.VITE_MCH_ID,
              appId: import.meta.env.VITE_APP_ID,
              package: packageStr
            },
            function (res: RedPacketResult) {
              console.log("requestMerchantTransfer返回 ==> ", res);

              if (res.err_msg === "requestMerchantTransfer:ok") {
                callback(3);
                resolve(res);
              } else if (res.err_msg === "requestMerchantTransfer:fail") {
                callback(5);
                showToast({
                  type: "fail",
                  message: "收款失败",
                  duration: 2000
                });
                reject(new Error(res.err_msg));
              } else if (res.err_msg === "requestMerchantTransfer:cancel") {
                callback(4);
                showToast({
                  type: "fail",
                  message: "红包未领取",
                  duration: 2000
                });
                reject(new Error(res.err_msg));
              } else if (res.err_msg === "requestMerchantTransfer:close") {
                callback(6);
                showToast({
                  type: "fail",
                  message: "关闭收款",
                  duration: 2000
                });
                reject(new Error(res.err_msg));
              } else {
                callback(7);
                showToast({
                  type: "fail",
                  message: "发放失败",
                  duration: 2000
                });
                reject(new Error(res.err_msg));
              }
            }
          );
        } else {
          callback(2);
          showToast({
            type: "fail",
            message: "你的微信版本过低，请更新至最新版本",
            duration: 3000
          });
          reject(new Error("微信版本不支持红包功能"));
        }
      }
    );
  });
};

export const isLaunching = ref(false);

function sendRedPacket(data, index) {
  lanuchRedPacket(data.packageInfo, (pullState: number) => {
    if (typeof data.sendPullState === "function") {
      console.log("sendPullState", pullState, index);
      data.sendPullState(pullState, data.sn);
    }
    if ([2, 4, 5, 6].includes(pullState) && index < 2) {
      console.log("from", pullState, index, "retry");
      showToast({
        type: "loading",
        message: "重试中...",
        duration: 500,
        loadingType: "spinner",
        forbidClick: true
      });
      setTimeout(() => {
        sendRedPacket(data, index + 1);
      }, 600);
    } else if (typeof data.callback === "function") {
      console.log("callback", pullState, index);

      isLaunching.value = false;
      data.callback(pullState);
    }
  });
}

export const launchRedPacket3Times = async data => {
  isLaunching.value = true;
  let index = 0;
  sendRedPacket(data, index);
};

// 使用示例
export const handleRedPacket = async (packageStr: string) => {
  try {
    const result = await lanuchRedPacket(packageStr, (pullState: number) => {
      console.log("pullState ==> ", pullState);
    });
    if (result.err_msg === "requestMerchantTransfer:ok") {
      // 处理成功逻辑
      return true;
    }
    return false;
  } catch (error) {
    console.error("红包发放出错:", error);
    return false;
  }
};
